#!/bin/bash
########################################################
# author: 以谁为师
# website: http://opsbase.cn
# description: Service installation script
#  bash <(curl -sL http://wuyou.run/scripts/deploy/system/init.sh)  pro-game-hsd-app-1
########################################################

# 判断是否root用户
if [ $(id -u) -ne 0 ]; then 
  color_msg error "### This script must be run as root !!!"
  exit 1
fi

#### -----------  打印颜色 ----------- #### 
function color_message() {
  case "$1" in
  "error"|"red")
    echo -e "\e[1;31m$2\e[0m"
    ;;
  "warn"|"yellow")
    echo -e "\e[1;33m$2\e[0m"
    ;;
  "info"|"blue")
    echo -e "\e[1;34m$2\e[0m"
    ;;
  "success"|"green")
    echo -e "\e[1;32m$2\e[0m"
    ;;
  esac
}



Set_passwd() {
  echo "tmp123456" | passwd --stdin "root" #修改密码
}


Init_Install() {
  
  # Set_passwd
  update_pkg
  Set_hostname $1
  Set_Selinux
  Set_iptables
  Set_ssh
  Set_limits
  Set_profile
  Set_timezone
  Optimize_kernel
}

update_pkg() {
  #### -----------  安装基础包 ----------- #### 
  which  yum &>/dev/null
  if [ $? -eq 0 ];then
    systemOS="centos"
    echo "*****************************************"
    color_message "info" ">> OS: $systemOS  start to initialize"
    echo "*****************************************"
    color_message  "info" "---- install base package ----"

    yum --debuglevel=1  install -y vim nfs-utils openssl-devel  pcre-devel  ntpdate \
    nc iotop sysstat dstat iftop nload iperf \
    lrzsz wget mlocate lsof telnet net-tools  dmidecode yum-utils 
  fi

  which  apt-get &>/dev/null
  if [ $? -eq 0 ];then
    systemOS="ubuntu"
    echo "*****************************************"
    color_message "info" ">> OS: $systemOS  start to initialize"
    echo "*****************************************"
    color_message  "info" "---- install base package ----"
    
    apt install vim ntpdate iotop sysstat dstat iftop \
    nload iperf lrzsz wget  lsof telnet net-tools  dmidecode 

  fi
}

Set_hostname() {
  # bash host_init.sh hostname 主机名传参
  if [ $# -lt 1 ]; then
    #传参少于1个
    color_message "warn" "---- Use default options  ----"
    HOSTNAME="TemplateOS"
    # 默认主机名TemplateOS
  else
    color_message "info" "---- Set  Hostname $HOSTNAME ----"
    HOSTNAME=$1


  fi

  if [ -f /etc/hostname ]; then
    echo "$HOSTNAME" >/etc/hostname
  fi
  sed -i "/HOSTNAME/c HOSTNAME=$HOSTNAME" /etc/sysconfig/network || echo "HOSTNAME=$HOSTNAME" >>/etc/sysconfig/network
  hostname $HOSTNAME
  grep $HOSTNAME /etc/hosts || echo "127.0.0.1 $HOSTNAME" >>/etc/hosts
}

Set_Selinux() {
  color_message "info" "---- close  selinux ----"
  if [ -s /etc/selinux/config ]; then
    setenforce 0
    sed -i 's/^SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
  fi
}

Set_iptables() {
  color_message "info" "---- setup iptables ----"
  if [ ! -f /etc/sysconfig/iptables ]; then
    yum install iptables-services -y
    chkconfig iptables on
    systemctl enable iptables
    systemctl disable firewalld
    systemctl stop firewalld
    service iptables restart
  fi

  iptables -F
  iptables -X
  iptables -t nat -F
  iptables -t nat -X
  iptables-save &>/dev/null
  service iptables save &>/dev/null
}

Set_timezone() {
  color_message "info" "---- Start configuring  Timezone ---- "
  \cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime &>/dev/null
  timedatectl set-timezone "Asia/Shanghai"
}

Set_ssh() {
  color_message "info" "---- Start configuring  SSH optimize---- "
  # sed -i '/^#Port/c Port 6022' /etc/ssh/sshd_config &>/dev/null # 默认端口修改
  grep '#UseDNS yes' /etc/ssh/sshd_config && sed -i "s/#UseDNS yes/UseDNS no/g" /etc/ssh/sshd_config
  grep '#AuthorizedKeysFile' /etc/ssh/sshd_config && sed -i "s/#AuthorizedKeysFile/AuthorizedKeysFile/" /etc/ssh/sshd_config
  grep 'GSSAPIAuthentication yes' /etc/ssh/sshd_config && sed -i "s/GSSAPIAuthentication yes/GSSAPIAuthentication no/g" /etc/ssh/sshd_config
  service sshd restart 
  # sshd服务重启
}

Set_limits() {
  color_message "info" "---- Start configuring  System limits ---- "
  chmod +x /etc/rc.local
  grep ulimit /etc/rc.local || echo ulimit -HSn 1048576 >>/etc/rc.local

  grep 1048576 /etc/security/limits.conf || cat >>/etc/security/limits.conf <<EOF
  * soft nproc 1048576
  * hard nproc 1048576
  * soft nofile 1048576
  * hard nofile 1048576
  * soft stack 1048575
EOF
}

Set_profile() {
  color_message "info" "---- Start configuring  /etc/profile ---- "
  grep vi ~/.bashrc || sed -i "/mv/a\alias vi='vim'" ~/.bashrc
  grep PS /etc/profile || echo '''PS1="\[\e[37;1m\][\[\e[32;1m\]\u\[\e[37;40m\]@\[\e[34;1m\]\h \[\e[0m\]\t \[\e[35;1m\]\W\[\e[37;1m\]]\[\e[m\]/\\$" ''' >>/etc/profile
  grep HISTTIMEFORMAT /etc/profile || cat >>/etc/profile <<EOF

#export TMOUT=7200
export HISTTIMEFORMAT="%F %T \$(whoami) " 
export HISTSIZE=10000 
EOF
}

Optimize_kernel() {
  color_message "info" "---- Kernel parameter optimize /etc/sysctl.conf ----"
  grep 65535 /etc/sysctl.conf || cat >/etc/sysctl.conf <<EOF
fs.file-max = 9999999
# 所有进程最大的文件数
fs.nr_open = 9999999
# 单个进程可分配的最大文件数
fs.aio-max-nr = 1048576
# 1024K；同时可以拥有的的异步IO请求数目

fs.inotify.max_queued_events = 327679
#  文件队列长度限制
fs.inotify.max_user_instances = 65535
#  每个real user ID可创建的inotify instatnces的数量上限，默认128.
fs.inotify.max_user_watches = 99999999
# 注册监听目录的数量限制


net.ipv4.ip_local_port_range = 9000 65000
# 被动端口

net.ipv4.tcp_keepalive_time = 180
# 客户端每次发送心跳的周期，默认值为7200s（2小时）；检测服务端是否活着
net.ipv4.tcp_keepalive_intvl = 15
# 探测包的发送间隔 默认75秒
net.ipv4.tcp_keepalive_probes = 5
# 没有接收到对方确认，继续发送保活探测包次数 默认9次

net.ipv4.tcp_tw_reuse = 1
#启用tcp重用
net.ipv4.tcp_fin_timeout = 3
# 决定FIN-WAIT-2状态的时间
net.ipv4.tcp_tw_recycle = 0
# TIME-WAIT的tcp快速回收；入口网关禁用此项


net.core.somaxconn = 8192
#监听队列的长度
net.netfilter.nf_conntrack_max = 262144
# 网络并发连接数等限制
net.nf_conntrack_max = 262144
# 网络并发连接数等限制

# vm.nr_hugepages=512 # 内核大页内存
# net.core.somaxconn = 65535 # 端口最大监听队列长度
# net.ipv4.tcp_max_syn_backlog  # SYN同步包的最大客户端数量

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
#禁止数据包重定向发送 (安全)

# kernel.shmall = 2097152
# kernel.shmmax = 1073741824
# kernel.shmmni = 4096
# kernel.sem = 250 32000 100 128
# net.core.rmem_default = 262144
# net.core.rmem_max = 4194304
# net.core.wmem_default = 262144
# net.core.wmem_max = 1048576

kernel.pid_max=655350
vm.max_map_count=262144

EOF
  sysctl -p
}


# -----------  执行中 ----------- # 
echo
Init_Install $1
# -----------  收尾配置 ----------- # 
if [ -f $0 ];then
  rm $0 -f # 回收此脚本文件
fi
 
echo 
color_message "success" ">> 脚本执行结束... "
# reboot